package com.acme.bankapp.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.acme.bankapp.domain.account.Account;
import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.client.Client;

public class BankReport {
	public static int getNbOfClients(Bank bank) {
		return bank.getClientsCount();
	}
	
	public static int getNbOfAccounts(Bank bank) {
		int nAccounts = 0;
		for (Client client : bank.getClients()) {
			nAccounts += client.getAccountsCount();
		}
		
		return nAccounts;
	}
	
	public static List<Account> getAccountsSortedBySum(Bank bank) {
		List<Account> allAccounts = new ArrayList<>();
		for (Client client : bank.getClients()) {
			allAccounts.addAll(client.getAccounts());
		}
		
		Collections.sort(allAccounts, new Comparator<Account>() {

			@Override
			public int compare(Account o1, Account o2) {
				double amount1 = o1.getMaximumAmountToWithdraw();
				double amount2 = o2.getMaximumAmountToWithdraw();
				
				if      (amount1 < amount2) return 1;
				else if (amount1 > amount2) return -1;
				else                        return 0;
			}
			
		});
		
		return allAccounts;
	}
	
	public static double getBankCredit(Bank bank) {
		double credit = 0;
		
		for (Client client : bank.getClients()) {
			for (Account account : client.getAccounts()) {
				if (account.getBalance() < 0) {
					credit -= account.getBalance();
				}
			}
		}
		
		return credit;
	}
	
	public static Map<Client, List<Account>> getClientsAccountsMap(Bank bank) {
		Map<Client, List<Account>> map = new HashMap<Client, List<Account>>();
		
		for (Client client : bank.getClients()) {
			List<Account> accounts = new ArrayList<>();
			for (Account account : client.getAccounts()) {
				accounts.add(account);
			}
			map.put(client, accounts);
		}
		
		return map;
	}
}
